package legumes.client.ui.admin.stall;

import legumes.client.resources.PNResources;
import legumes.client.services.callbacks.SaveStallCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.client.ui.widgets.utils.Formatters;
import legumes.shared.domain.Menu;
import legumes.shared.domain.MenuItem;
import legumes.shared.domain.Quantity;
import legumes.shared.domain.SellSession;
import legumes.shared.domain.Unit;

import com.google.gwt.core.client.GWT;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.FormItemInputTransformer;
import com.smartgwt.client.widgets.form.FormItemValueFormatter;
import com.smartgwt.client.widgets.form.fields.FloatItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.form.validator.FloatPrecisionValidator;
import com.smartgwt.client.widgets.form.validator.FloatRangeValidator;
import com.smartgwt.client.widgets.form.validator.IsFloatValidator;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.SummaryFunction;
import com.smartgwt.client.widgets.grid.events.EditCompleteEvent;
import com.smartgwt.client.widgets.grid.events.EditCompleteHandler;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;

public class BasketInsidePanel extends VLayout {

	private FloatItem halfBaskerPriceTI;
    private FloatItem wholeBaskerPriceTI;
    
	private ListGrid basketGrid;
	private SellSession sellSession;
	
	public BasketInsidePanel() {
		super();
		setWidth100();
		setHeight("50%");
        
		setShowEdges(true);
		setMembersMargin(5);  
        setLayoutMargin(10); 
        
		build();
	}
	
	public void initData(SellSession sellSession_){
		sellSession = sellSession_;
		Menu menu = sellSession_.getStall().getMenu();
		int i = 0;
		ListGridRecord[] records = new ListGridRecord[menu.getMenuWholeItems().size()];
		for (MenuItem mi : menu.getMenuWholeItems()) {
			ListGridRecord record = new ListGridRecord();
			record.setAttribute("isSelected", true);
			record.setAttribute("prix", mi.getOnSaleProduct().getPrice().getAmount());
			record.setAttribute("libelle", mi.getArticleName());
			record.setAttribute("quantite", mi.getQuantity().getValue());
			record.setAttribute("quantiteUnit", mi.getQuantity().getUnitAsEnum().getDisplayName() );
//			if(mi!= null && mi.getOnSaleProduct() != null && mi.getOnSaleProduct().getProduct() != null 
//					&&  mi.getOnSaleProduct().getProduct().getProductType() != null){
//				record.setAttribute("categorie", mi.getOnSaleProduct().getProduct().getProductType() );
//			} else {
//				record.setAttribute("categorie", "L");
//			}
			records[i] = record;
			i++;
		}
		basketGrid.setRecords(records);

		halfBaskerPriceTI.setValue(menu.getHalfPrice());
		wholeBaskerPriceTI.setValue(menu.getWholePrice());
	}
	
	private void saveOnServer(){
		RPCCallSequencer callSequencer = new RPCCallSequencer("Enregistrement en cours...");
		final SaveStallCallback saveStallCallback = new SaveStallCallback(
				sellSession.getStall());
		callSequencer.addCall(saveStallCallback);
		callSequencer.callSequence();
	}
	
	private void build(){

		ToolStrip toolStrip = new ToolStrip();
		toolStrip.setWidth100();
		toolStrip.setHeight(21);
		
		
		ToolStripButton addProductButton = new ToolStripButton();  
		addProductButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				ListGridRecord record = new ListGridRecord();
				record.setAttribute("isSelected", true);
				record.setAttribute("prix", 0f);
				record.setAttribute("quantite", 1f);
				record.setAttribute("quantiteUnit", Unit.KG.getDisplayName() );
				record.setAttribute("categorie", "L");
				
				basketGrid.startEditingNew(record);
			}
		});
		addProductButton.setIcon(PNResources.INSTANCE.addIcon().getURL());  
		addProductButton.setTooltip("Ajouter un produit");
        toolStrip.addButton(addProductButton);
       
        ToolStripButton delProductButton = new ToolStripButton();  
        delProductButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				final ListGridRecord [] selectedRecords = basketGrid.getSelection();
				
				BooleanCallback bc = new BooleanCallback() {
					
					@Override
					public void execute(Boolean value) {
						if( value.booleanValue() ){
							
							for(ListGridRecord r : selectedRecords){
								String productName = r.getAttributeAsString("libelle");
								
								MenuItem MenuItem = sellSession.getStall().getMenu().findWholeMenuItemFor(productName);
								sellSession.getStall().getMenu().getMenuWholeItems().remove(MenuItem);
							}
							saveOnServer();
							
							basketGrid.removeSelectedData();
						}
					}
				};
				if(selectedRecords == null || selectedRecords.length <= 0){
					SC.say("Vous devez s&eacute;lectionner des produits dans la grille pour les supprimer.");
				} else if(selectedRecords.length==1) {
					String productName = selectedRecords[0].getAttributeAsString("libelle");
					SC.confirm("Suppression d'un produit du panier", 
							"Etes vous sur de vouloir supprimer le produit " + productName + "  ?", 
							bc);
				} else {
					SC.confirm("Suppression de produits du panier", 
							"Etes vous sur de vouloir supprimer les " + selectedRecords.length +" produits s&eacute;lectionn&eacute;s du panier ?", 
							bc);
				}
			}
		});
        delProductButton.setIcon(PNResources.INSTANCE.deleteIcon().getURL());  
        delProductButton.setTooltip("Supprimer les produits s&eacute;lectionn&eacute;s...");  
        toolStrip.addButton(delProductButton);
        
        toolStrip.addFill();
        StaticTextItem sti = 
			new StaticTextItem("adminHeaderInBasketGrid", "");
		sti.setWrap(false);
		sti.setShowTitle(false);
		sti.setValue("Contenu du panier");
		toolStrip.addFormItem(sti);
		toolStrip.addFill();

        FormItemInputTransformer fiit = new FormItemInputTransformer() {
			private float parseOldValue(Object oldValue){
				Float f = 0.0f;
				try{
					f = (Float)oldValue;
				}catch(Exception e4_){
					try{
						f = new Float( (Integer)oldValue );
					}catch(Exception e5_){
					}
				}
				return f;
			}
			@Override
			public Object transformInput(DynamicForm form, FormItem item, Object value,
					Object oldValue) {
				Float f = 0.0f;
				try{
					f = Float.parseFloat( ((String) value).replace(',', '.') );
				} catch(Exception e_){
					try{
						f = Float.parseFloat( value.toString().replace(',', '.') );
					}catch(Exception e2_){
						f = parseOldValue(oldValue);
					}
				}
				return f;
			}
		};

		FormItemValueFormatter fivf = new FormItemValueFormatter() {
			
			@Override
			public String formatValue(Object value_, Record record, DynamicForm form,
					FormItem item) {
				return value_ == null ? null : Formatters.formatQuantity(value_);
			}
		};
		
		FloatPrecisionValidator fpv = new FloatPrecisionValidator();
        fpv.setPrecision(2);
        fpv.setRoundToPrecision(2);
        FloatRangeValidator frv = new FloatRangeValidator();
        frv.setMin(0.0f);
        frv.setMax(1000.0f);
        
        wholeBaskerPriceTI = new FloatItem("wholeBaskerPriceTI", "Prix du panier");
        wholeBaskerPriceTI.setHint(" &#8364;");
        wholeBaskerPriceTI.setWidth(50);
        wholeBaskerPriceTI.setWrapTitle(false);
        wholeBaskerPriceTI.setValue(14.50f);
        wholeBaskerPriceTI.setEndRow(false);
        wholeBaskerPriceTI.setValidators(new IsFloatValidator(), frv, fpv);
        wholeBaskerPriceTI.setEditorValueFormatter(fivf);
        wholeBaskerPriceTI.setValidateOnChange(true);
        wholeBaskerPriceTI.setInputFormat("#0.00");
        wholeBaskerPriceTI.setInputTransformer( fiit );
        wholeBaskerPriceTI.addChangedHandler(new ChangedHandler() {
			
			@Override
			public void onChanged(ChangedEvent event) {
				try{
					wholeBaskerPriceTI.validate();
					float wholePrice = wholeBaskerPriceTI.getValueAsFloat();
					sellSession.getStall().getMenu().setWholePrice(wholePrice);
					saveOnServer();
				} catch(Exception e_){
					GWT.log("ERROR while editing wholeBaskerPriceTI");
				}
				
			}
		});
        toolStrip.addFormItem(wholeBaskerPriceTI);
        
        halfBaskerPriceTI = new FloatItem();
        halfBaskerPriceTI.setHint(" &#8364;");
        halfBaskerPriceTI.setWidth(50);
        halfBaskerPriceTI.setWrapTitle(false);
        halfBaskerPriceTI.setStartRow(false);
        halfBaskerPriceTI.setTitle("Prix du demi panier");
        halfBaskerPriceTI.setValue(8f);
        halfBaskerPriceTI.setValidateOnChange(true);
        halfBaskerPriceTI.setValidators(new IsFloatValidator(), frv, fpv);
        halfBaskerPriceTI.setEditorValueFormatter(fivf);
        halfBaskerPriceTI.setInputTransformer( fiit );
        halfBaskerPriceTI.addChangedHandler(new ChangedHandler() {
			
			@Override
			public void onChanged(ChangedEvent event) {
				try{
					halfBaskerPriceTI.validate();
					float halfPrice = halfBaskerPriceTI.getValueAsFloat();
					sellSession.getStall().getMenu().setHalfPrice(halfPrice);
					saveOnServer();
				} catch(Exception e_){
					GWT.log("ERROR while editing halfBaskerPriceTI");
				}
				
			}
		});
        toolStrip.addFormItem(halfBaskerPriceTI);
        
        basketGrid = new ListGrid();
        basketGrid.setShowRollOverCanvas(true);  
        basketGrid.setCanEdit(true);
        basketGrid.setWidth100();
        basketGrid.setHeight("50%");  
        basketGrid.setShowAllRecords(true);  
        basketGrid.setCellHeight(22);  
        
        basketGrid.setSelectionType(SelectionStyle.SIMPLE);  
        basketGrid.setSelectionAppearance(SelectionAppearance.ROW_STYLE);
        basketGrid.setEditByCell(false);
        basketGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX); 
//        basketGrid.setHeaderSpans(  
//                 new HeaderSpan("Les l&eacute;gumes du maraich&eacute;", new String[]{"libelle", "prix", "total"})  
//               );
        
        ListGridField libelleField = new ListGridField("libelle", "Produit", 150);
        libelleField.setShowGridSummary(true); 
        libelleField.setShowGroupSummary(true);
        libelleField.setCanEdit(true);
        libelleField.setSummaryFunction(new SummaryFunction(){

            @Override
            public Object getSummaryValue(Record[] records_, ListGridField field_) {
                int count = 0;
                for(Record r : records_){
                    if( r.getAttributeAsBoolean("isSelected") ){
                        count++;
                    }
                }
                
                
                return count>1 ? count + " s&eacute;lectionn&eacute;s" : count + " s&eacute;lectionn&eacute;";
            }
            
        });  
        
        ListGridField prixField = new ListGridField("prix", "Prix", 70);
        prixField.setType(ListGridFieldType.FLOAT);
        prixField.setShowGridSummary(false);
        prixField.setShowGroupSummary(false);
        prixField.setCanEdit(true);
        prixField.setCellFormatter(new CellFormatter(){

            @Override
            public String format(Object value_, ListGridRecord record_, int rowNum_, int colNum_) {
                return value_ == null ? null : Formatters.formatPrice(value_, true);
            }
            
        });
        
        ListGridField quantityAmountField = new ListGridField("quantite", "Quantit&eacute;", 50);
        quantityAmountField.setType(ListGridFieldType.FLOAT);
        quantityAmountField.setAlign(Alignment.RIGHT);
        quantityAmountField.setCanEdit(true);
        
        
        ListGridField quantityUnitField = new ListGridField("quantiteUnit", "Unit&eacute; Quantit&eacute;", 100);
        quantityUnitField.setValueMap(Unit.G.getDisplayName(), Unit.KG.getDisplayName(), Unit.L.getDisplayName(), Unit.UNITY.getDisplayName());
        quantityUnitField.setAlign(Alignment.LEFT);
        quantityUnitField.setCanEdit(true);
        
        
        basketGrid.setFields(libelleField, prixField, quantityAmountField, quantityUnitField);  
        basketGrid.addEditCompleteHandler(new EditCompleteHandler() {
			
			@Override
			public void onEditComplete(EditCompleteEvent event) {
				ListGridRecord lgr = basketGrid.getRecord(event.getRowNum());
				String menuItemName = lgr.getAttributeAsString("libelle");
				MenuItem miToAdd = sellSession.getStall().getMenu().findWholeMenuItemFor(menuItemName);
				if( miToAdd == null){
					miToAdd = new MenuItem();
					miToAdd.setId( sellSession.getStall().getMenu().getDate() );
					sellSession.getStall().getMenu().addMenuWholeItem(miToAdd);
				}
//				miToAdd.setMenuProduct(menuItemName);
				float price = 0.0f;
				try{
					price = lgr.getAttributeAsFloat("prix");
				} catch(Exception e_){
					price = Float.parseFloat(lgr.getAttribute("prix"));
				}
				miToAdd.getOnSaleProduct().getPrice().setAmount(price );
				
				Quantity q = new Quantity();
				q.setValue(lgr.getAttributeAsFloat("quantite"));
				q.setUnit( Unit.fromDisplayName(lgr.getAttributeAsString("quantiteUnit")).name() );
				miToAdd.setQuantity(q);
				
				
				saveOnServer();
			}
		});
        
        setMembers(toolStrip, basketGrid);
    }
}
